import React, { useState, useEffect, useRef } from 'react';
import { Button, DatePicker, ConfigProvider, Input, Switch, message, Skeleton } from 'antd';
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import { RollbackOutlined, SearchOutlined } from '@ant-design/icons';
import 'dayjs/locale/zh-cn';
import MultiSelectTable from './TopicProvider';
import axios from 'axios';
import DynamicPagination from '../components/pages/DynamicPagination';

axios.defaults.baseURL = 'http://localhost:3000/';
dayjs.locale('zh-cn');
const { RangePicker } = DatePicker;

export default function Topic() {
    const [topicList, setTopicList] = useState([]);
    const [value, setValue] = useState('');
    const [totalRecords, setTotalRecords] = useState(0);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(2);
    const [dateRange, setDateRange] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [loading, setLoading] = useState(true);
    const styleRef = useRef(null);

    const columns = [
        {
            align: 'center',
            title: '话题内容',
            key: 'content',
            dataIndex: 'content',
            render: (_, record) => (
                <span>{record.content}</span>
            )
        },
        {
            align: 'center',
            title: '内容数量',
            dataIndex: 'nid',
            key: 'nid',
            render: () => (
                <span>200</span>
            )
        },
        {
            align: 'center',
            title: '浏览',
            dataIndex: 'liu',
            key: 'liu',
            render: (_, record) => (
                <span>{record.liu}</span>
            )
        },
        {
            align: 'center',
            title: '分享',
            dataIndex: 'fen',
            key: 'fen',
            render: (_, record) => (
                <span>{record.fen}</span>
            )
        },
        {
            align: 'center',
            title: '关注',
            key: 'guan',
            dataIndex: 'guan',
            render: (_, record) => (
                <span>{record.guan}</span>
            )
        },
        {
            align: 'center',
            title: '最后更新人',
            key: 'geng',
            dataIndex: 'geng',
            render: (_, record) => (
                <span>{record.geng}</span>
            )
        },
        {
            align: 'center',
            title: '最后更新时间',
            key: 'end_time',
            dataIndex: 'end_time',
            render: (_, record) => (
                <span>{dayjs(record.start_time).format('YYYY-MM-DD HH:mm:ss')}</span>
            )
        },
        {
            align: 'center',
            title: '状态',
            key: 'status',
            dataIndex:'status',
            render: (_, record) => (
                <Switch checkedChildren="启用" unCheckedChildren="禁用" checked={record.status} />
            )
        },
        {
            align: 'center',
            title: '操作',
            render: (_, record) => (
                <span>
                    <a onClick={() => handleEdit(record)} style={{ marginLeft: 16 }}>
                        编辑
                    </a>
                    <a style={{ color:'red' }} onClick={() => handleDelete(record._id)} style={{ marginLeft:16}}>
                        删除
                    </a>
                </span>
            )
        },
    ];

    const getTopicList = async () => {
        setLoading(true);
        try {
            const { data: { list, total } } = await axios.get('/kai/getliving', {
                params: {
                    name: value,
                    page,
                    pagesize: pageSize,
                    startdate: dateRange[0]? dayjs(dateRange[0]).format('YYYY-MM-DD') : null,
                    endate: dateRange[1]? dayjs(dateRange[1]).format('YYYY-MM-DD') : null
                }
            });
            setTopicList(list);
            setTotalRecords(total);
        } catch (error) {
            console.error('获取话题列表失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handlePageChange = (newPage, newPageSize) => {
        setPage(newPage);
        setPageSize(newPageSize);
        getTopicList(); // 分页操作时重新请求数据并显示骨架屏
    };

    const handleShowSizeChange = (current, size) => {
        setPage(current);
        setPageSize(size);
        getTopicList(); // 改变每页显示数量时重新请求数据并显示骨架屏
    };

    const sou = () => {
        if (value.length > 0) {
            getTopicList();
        }
    };

    const qu = () => {
        if (value.length > 0) {
            setValue(value.slice(0, -1));
        }
    };

    const handleRowSelectionChange = (selectedRowKeys, selectedRows) => {
        console.log('选中的行键:', selectedRowKeys);
        console.log('选中的行数据:', selectedRows);
        setSelectedRowKeys(selectedRowKeys);
        setSelectedRows(selectedRows);
    };

    const handleBatchDelete = async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的话题');
            return;
        }
        try {
            const ids = selectedRowKeys.map(key => key);
            await axios.delete('/kai/deleteTopics', { data: { ids } });
            message.success('批量删除成功');
            setPage(1);
            getTopicList();
            setSelectedRowKeys([]);
            setSelectedRows([]);
        } catch (error) {
            message.error('批量删除失败');
            console.error('批量删除失败:', error);
        }
    };

    useEffect(() => {
        getTopicList();
        const style = document.createElement('style');
        style.innerHTML = `
            @keyframes skeleton-loading {
                0% {
                    background-color: #eaeaea;
                }
                50% {
                    background-color: #f5f5f5;
                }
                100% {
                    background-color: #eaeaea;
                }
            }
        `;
        document.head.appendChild(style);
        styleRef.current = style;
        return () => {
            if (styleRef.current) {
                document.head.removeChild(styleRef.current);
            }
        };
    }, []);

    return (
        <div style={{
            scrollbarWidth: 'none',
            overflowY: 'auto',
            margin: 'auto',
            width: '70%',
            height: '100%',
        }}>
            {/* 搜索区域 */}
            <div style={{ marginTop: '0.6rem', overflow: 'hidden', backgroundColor: 'white', width: '100%', height: '24%', borderRadius: '20px' }}>
                <div style={{ display: 'flex', margin: '0.6rem' }}>
                    {loading ? (
                        <Skeleton.Input
                            active
                            style={{
                                width: '0.16rem',
                                height: '0.6rem',
                                borderRadius: '0.1rem',
                                backgroundColor: '#eaeaea',
                                animation: 'skeleton-loading 1.5s infinite'
                            }}
                        />
                    ) : (
                        <div style={{ width: '0.16rem', marginTop: '0.1rem', borderRadius: '0.1rem', height: '0.6rem', backgroundColor: '#3dd4a7' }}></div>
                    )}
                    {loading ? (
                        <Skeleton.Input
                            active
                            style={{
                                width: '1.2rem',
                                height: '0.6rem',
                                marginLeft: '0.2rem',
                                backgroundColor: '#eaeaea',
                                animation: 'skeleton-loading 1.5s infinite'
                            }}
                        />
                    ) : (
                        <div style={{ fontSize: '0.5rem', marginLeft: '0.2rem' }}>话题管理</div>
                    )}
                </div>
                <div style={{ width: '100%', display: 'flex', fontSize: '0.4rem', color: '#999', margin: '1rem 0.6rem' }}>
                    {loading ? (
                        <Skeleton.Input
                            active
                            style={{
                                width: '1.2rem',
                                height: '0.6rem',
                                backgroundColor: '#eaeaea',
                                animation: 'skeleton-loading 1.5s infinite'
                            }}
                        />
                    ) : (
                        <div>更新日期</div>
                    )}
                    <div style={{ margin: '-0.2rem 0.5rem' }}>
                        {loading ? (
                            <Skeleton.Input
                                active
                                style={{
                                    width: '10rem',
                                    height: '1rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        ) : (
                            <ConfigProvider locale={locale}>
                                <RangePicker
                                    style={{ height: '1rem', width: '10rem' }}
                                    onChange={(dates) => setDateRange(dates)}
                                />
                            </ConfigProvider>
                        )}
                    </div>
                    <div style={{ margin: '-0.2rem 0.1rem' }}>
                        {loading ? (
                            <Skeleton.Input
                                active
                                style={{
                                    width: '10rem',
                                    height: '1rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        ) : (
                            <Input
                                onChange={(e) => setValue(e.target.value)}
                                value={value}
                                style={{ height: '1rem', width: '10rem' }}
                                placeholder="请输入关键字"
                            />
                        )}
                    </div>
                    <div>
                        {loading ? (
                            <Skeleton.Button
                                active
                                style={{
                                    width: '1rem',
                                    height: '1rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        ) : (
                            <Button
                                onClick={sou}
                                style={{
                                    textAlign: 'center',
                                    lineHeight: '1rem',
                                    margin: '-0.2rem 0.3rem',
                                    width: '1rem',
                                    height: '1rem',
                                    background: '#5adbb5',
                                    color: 'white',
                                    borderRadius: '0.1rem'
                                }}
                                type="primary"
                                icon={<SearchOutlined />}
                            />
                        )}
                    </div>
                    <div>
                        {loading ? (
                            <Skeleton.Button
                                active
                                style={{
                                    width: '1rem',
                                    height: '1rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        ) : (
                            <Button
                                onClick={qu}
                                style={{
                                    textAlign: 'center',
                                    lineHeight: '1rem',
                                    margin: '-0.2rem 0.3rem',
                                    width: '1rem',
                                    height: '1rem',
                                    color: 'black'
                                }}
                                type="primary"
                                color='default'
                                variant="outlined"
                                icon={<RollbackOutlined />}
                            />
                        )}
                    </div>
                </div>
            </div>
            {/* 表格和操作按钮区域 */}
            <div style={{ marginTop: '0.6rem', overflow: 'hidden', marginBottom: '1.25rem', backgroundColor: 'white', width: '100%', borderRadius: '20px' }}>
                <div style={{ margin: '0.5rem 25rem', display: 'flex' }}>
                    {loading ? (
                        <>
                            <Skeleton.Button
                                active
                                style={{
                                    width: '1.8rem',
                                    height: '1rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                            <Skeleton.Button
                                active
                                style={{
                                    width: '2.4rem',
                                    height: '1rem',
                                    marginLeft: '0.5rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        </>
                    ) : (
                        <>
                            <Button
                                style={{ background: '#5adbb5', color: 'white', width: '1.8rem', height: '1rem' }}
                                variant="solid"
                            >
                                新增
                            </Button>
                            <Button
                                onClick={handleBatchDelete}
                                style={{ marginLeft: '0.5rem', width: '2.4rem', height: '1rem' }}
                                color="default"
                                variant="outlined"
                            >
                                批量删除
                            </Button>
                        </>
                    )}
                </div>
                <div style={{ width: '92%', margin: '0 auto' }}>
                    {loading ? (
                        <Skeleton
                            paragraph={{ rows: 5 }}
                            active
                            style={{
                                backgroundColor: '#eaeaea',
                                animation: 'skeleton-loading 1.5s infinite'
                            }}
                        />
                    ) : (
                        <MultiSelectTable
                            columns={columns}
                            dataSource={topicList}
                            onRowSelectionChange={handleRowSelectionChange}
                        />
                    )}
                    <div style={{ width: '100%', margin: '0.5rem 15.6rem' }}>
                        {loading ? (
                            <Skeleton.Input
                                active
                                style={{
                                    width: '10rem',
                                    height: '0.6rem',
                                    backgroundColor: '#eaeaea',
                                    animation: 'skeleton-loading 1.5s infinite'
                                }}
                            />
                        ) : (
                            <DynamicPagination
                                total={totalRecords}
                                pageSize={pageSize}
                                currentPage={page}
                                defaultCurrent={page}
                                defaultPageSize={pageSize}
                                showQuickJumper={true}
                                onPageChange={handlePageChange}
                                onShowSizeChange={handleShowSizeChange}
                            />
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}